package com.kuaidao.sys.aop;

import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Slf4j
public class WebLogAspect {

    /*private Logger logger = LoggerFactory.getLogger(this.getClass());*/

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    //1.pointCut 切入点
    @Pointcut("execution(public * com.kuaidao.sys.controller..*.*(..))")
    public void webLog() {

    }

    // 前置
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint)throws Throwable{
        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request =requestAttributes.getRequest();

        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

    }

    //后置
    @AfterReturning(returning = "ret",pointcut = "webLog()")
    public void doAfterReturnning(Object ret){
        //处理完请求返回内容
        log.info("RESPONSE : " +ret);
        log.info("SPEND TIME :"+(System.currentTimeMillis() - startTime.get()));
    }

}
